//
//  ScanViewController.m
//  Auditory
//
//  Created by 寒竹子 on 15/5/16.
//  Copyright (c) 2015年 寒竹子. All rights reserved.
//  二维码扫描

#define ScanHeight 220.0f
#define ScanWidth  220.0f

#import "ScanViewController.h"
#import "ZBarSDK.h"

@interface ScanViewController ()<ZBarReaderDelegate>
@property (nonatomic, strong) UIImageView * imageView;
@property (nonatomic, strong) UIView * scanLine; // 扫描仪
@property (nonatomic, strong) NSTimer * timer;
@end

@implementation ScanViewController

/**
 * @brief  初始化UI
 *
 * @param
 * @return
 */
- (void)setupUI
{
    self.view.backgroundColor = RGB(248, 248, 248, 1.0f);
    
    // 设置导航
    [self setupNav];
    
    [self scanAction];
}

/**
 * @brief  设置导航
 *
 * @param
 * @return
 */
- (void)setupNav
{
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * backItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    // 扫一扫
    UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    [btn setTitle:@"扫一扫" forState:UIControlStateNormal];
    [btn setTitleColor:RGB(10, 10, 10, 1.0f) forState:UIControlStateNormal];
    [btn setTitleColor:RGB(100, 100, 100, 1.0f) forState:UIControlStateHighlighted];
    btn.titleLabel.font = TextFont(15.0f);
    [btn addTarget:self action:@selector(scanAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    UILabel * titleView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100.0f, 25.0f)];
    titleView.textAlignment = NSTextAlignmentCenter;
    titleView.font = TextFont(18.0f);
    titleView.text = @"二维码扫描";
    titleView.textColor = RGB(10, 10, 10, 1.0f);
    
    [self addNavigationWithTitle:nil leftItem:backItem rightItem:rightItem titleView:titleView];
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 * @brief  起一个定时器
 *
 * @param
 * @return
 */
- (void)startTimer
{
    _timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(updateScanLine) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

/**
 * @brief  停止定时器
 *
 * @param
 * @return
 */
- (void)stopTimer
{
    if ([_timer isValid]) {
        [_timer invalidate];
        _timer = nil;
    }
}

/**
 * @brief  扫描二维码
 *
 * @param
 * @return
 */
- (void)scanAction
{
    ZBarReaderViewController * readerVc = [[ZBarReaderViewController alloc] init];
    readerVc.readerDelegate = self;
    
    // 非全屏
    readerVc.wantsFullScreenLayout = NO;
    
    // 隐藏底部控制按钮
    readerVc.showsZBarControls = NO;
    
    // 设置自己定义的界面
    [self setOverlayPickerView:readerVc];
    
    ZBarImageScanner * scanner = readerVc.scanner;
    [scanner setSymbology:ZBAR_I25 config:ZBAR_CFG_ENABLE to:0];
    
    [self presentViewController:readerVc animated:YES completion:nil];
    [self startTimer];
}

- (void)setOverlayPickerView:(ZBarReaderViewController *)readerVc
{
    // 清除原有的控件
    for (UIView * temp in [readerVc.view subviews]) {
        for (UIButton * btn in [temp subviews]) {
            if ([btn isKindOfClass:[UIButton class]]) {
                [btn removeFromSuperview];
            }
        }
        
        for (UIToolbar * toolBar in [temp subviews]) {
            if ([toolBar isKindOfClass:[UIToolbar class]]) {
                [toolBar setHidden:YES];
                
                [toolBar removeFromSuperview];
            }
        }
    }
    
    // 画中间的基准线
    _scanLine = [[UIView alloc] initWithFrame:CGRectMake((self.view.frame.size.width - ScanWidth) / 2.0f, (self.view.frame.size.height - ScanHeight) / 2.0f, ScanWidth, 1)];
    _scanLine.backgroundColor = [UIColor redColor];
    
    [readerVc.view addSubview:_scanLine];
    
    // 最上部的View
    UIView * upView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, (self.view.frame.size.height - ScanHeight) / 2.0f)];
    upView.alpha = .4f;
    upView.backgroundColor = [UIColor blackColor];
    
    [readerVc.view addSubview:upView];
    
    // 用于说明的label
    UILabel * infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, self.view.frame.size.width - 40, 60)];
    infoLabel.backgroundColor = [UIColor clearColor];
    infoLabel.numberOfLines = 2;
    infoLabel.font = TextFont(15.0f);
    infoLabel.textColor = [UIColor redColor];
    infoLabel.text = @"将二维码置于矩形方框内，离手机摄像头10CM左右，系统会自动识别。";
    [upView addSubview:infoLabel];
    
    // 左侧的view
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(upView.frame), (self.view.frame.size.width - ScanWidth) / 2.0f, ScanHeight)];
    
    leftView.alpha = 0.4;
    
    leftView.backgroundColor = [UIColor blackColor];
    
    [readerVc.view addSubview:leftView];
    
    // 右侧的view
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftView.frame) + ScanWidth, leftView.frame.origin.y, (self.view.frame.size.width - ScanWidth) / 2.0f, ScanHeight)];
    
    rightView.alpha = 0.4;
    
    rightView.backgroundColor = [UIColor blackColor];
    
    [readerVc.view addSubview:rightView];
    
    //底部view
    
    UIView * downView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(leftView.frame), self.view.frame.size.width, self.view.frame.size.height - CGRectGetMaxY(leftView.frame))];
    
    downView.alpha = 0.4;
    
    downView.backgroundColor = [UIColor blackColor];
    
    [readerVc.view addSubview:downView];
    
    // 取消操作的按钮
    UIButton * cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake((self.view.frame.size.width - 55) / 2.0f, 30, 70, 70.0f)];
    [cancelBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
    [downView addSubview:cancelBtn];
}

/**
 * @brief  更新扫描
 *
 * @param
 * @return
 */
- (void)updateScanLine
{
    // 确定起始坐标
    CGFloat startY = (self.view.frame.size.height - ScanHeight) / 2.0f + 30.0f;
    
    CGRect startFrame = _scanLine.frame;
    startFrame.origin.y = startY;
    _scanLine.frame = startFrame;
    
    [UIView animateWithDuration:2.0f animations:^{
        // 确定终止坐标
        CGFloat endY = (self.view.frame.size.height - ScanHeight) / 2.0f + ScanHeight + 30.0f;
        CGRect endFrame = _scanLine.frame;
        endFrame.origin.y = endY;
        _scanLine.frame = endFrame;
        
    } completion:^(BOOL finished) {
        CGFloat endY = (self.view.frame.size.height - ScanHeight) / 2.0f + ScanHeight + 30.0f;
        CGRect endFrame = _scanLine.frame;
        endFrame.origin.y = endY;
        _scanLine.frame = endFrame;
    }];
}

/**
 * @brief  关闭扫描页面
 *
 * @param
 * @return
 */
- (void)closeAction
{
    [self stopTimer];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

#pragma mark ZBarSDKDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    id<NSFastEnumeration> results = [info objectForKey:ZBarReaderControllerResults];
    ZBarSymbol * symbol;
    for(symbol in results)
        break;
    
    // 扫描到图片
    _imageView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self stopTimer];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    if (symbol.data) {
        // 扫描到内容
        NSLog(@"symbol.data: %@", symbol.data);
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:symbol.data]];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
